package syn;

/**
 * @author zfj
 * @date 2021/10/17 -11:42
 */
public class UnSafeBuyTicket {
	public static void main(String[] args) {
		BuyTicket station = new BuyTicket();
		new Thread(station,"我").start();
		new Thread(station,"你").start();
		new Thread(station,"黄牛").start();
	}
}
class BuyTicket implements Runnable{

	/**
	 * When an object implementing interface <code>Runnable</code> is used
	 * to create a thread, starting the thread causes the object's
	 * <code>run</code> method to be called in that separately executing
	 * thread.
	 * <p>
	 * The general contract of the method <code>run</code> is that it may
	 * take any action whatsoever.
	 *
	 * @see Thread#run()
	 */
	private int ticketNum=10;
	boolean flog=true;
	@Override
	public void run() {
		//买票
		while (flog){
			try {
				buy();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	//同步方法，锁是this
	private synchronized void buy() throws InterruptedException {
		//判断是否有票
		if (ticketNum<=0){
			flog=false;
			return;
		}
		//模拟延时
		Thread.sleep(100);
		//买票
		System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
	}
}